const validate = require("validate.js");
const fs = require("fs");
const path = require("path");
const { NotFoundError, DataFaildError } = require("../utils/errors");
const { addMessage, getMessage, deleteMessage } = require("../Dao/messageDao");
const { FormatJson } = require("../utils/tool");
const { getOneBlog } = require("../Dao/blogDao");
const BlogModel = require("../Dao/models/BlogModel");
/**
 * 产生随机的头像路径
 * @param {*} dir 路径 
 */
function RandomAvatartUrl(dir) {
    return new Promise(resolve => {
        fs.readdir(dir, (err, files) => {
            if (err) throw new NotFoundError();
            resolve(files);
        })
    })
}

// 添加评论或者留言
module.exports.addMessageServices = async function (info) {
    // 审定规则
    const ValidateRules = {
        nickname: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        content: {
            presence: {
                allowEmpty: false
            },
            type: "string"
        },
        blogId: {
            type: "string"
        }
    }
    console.log(info, 'infos')
    const result = validate.validate(info, ValidateRules)
    if (!result) {
        // 初始化，创建创建时间
        info.createDate = JSON.stringify(Date.now());
        // 创建头像的路径
        const AvatarUrls = await RandomAvatartUrl(path.resolve(__dirname, "../public/static/avatar"));
        const RandomIndex = Math.floor(Math.random() * AvatarUrls.length);
        info.avatar = "/static/avatar/" + AvatarUrls[RandomIndex];
        const data = await addMessage(info);
        if (info.blogId) {
            // 如果是blogId有的话就添加，对应其文字评论加1
            const Blog = await getOneBlog(data.blogId);
            data.blog = {
                id: Blog.id,
                title: Blog.title
            }
            // 返回的内容
            const addBlogCOmment = await BlogModel.findByPk(info.blogId);
            addBlogCOmment.commentNumber++;
            addBlogCOmment.save();
        }
        delete data.blogId;
        return FormatJson(0, "", data)

    } else {
        throw new DataFaildError(JSON.stringify(result));
    }
}

// 获取评论或者留言
module.exports.getMessageServices = async function (query) {
    let data = await getMessage(query);
    for (const items of data.rows) {
        delete items.deletedAt;
        delete items.blogId;
    }
    if (query.blogid) {
        for (const items of data.rows) {
            items.blog = {
                id: items.blog.id,
                title: items.blog.title
            }
        }
    }
    data = {
        total: data.count,
        rows: data.rows
    }
    return FormatJson(0, "", data)
}

// 删除评论或者留言
module.exports.deleteMessageServices = async function (id) {
    return await deleteMessage(id) > 0 ? FormatJson(0, "", true) : FormatJson(0, "", false);
}